﻿using Subsonic.Data;

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Subsonic.ViewModels;
using MichMan.Utilities.Requests;
using Windows.Storage.Streams;
using Windows.ApplicationModel;
using Windows.Storage;
using System.Threading.Tasks;

// The Item Detail Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234232

namespace Subsonic
{
    /// <summary>
    /// A page that displays details for a single item within a group while allowing gestures to
    /// flip through other items belonging to the same group.
    /// </summary>
    public sealed partial class ItemDetailPage : Subsonic.Common.LayoutAwarePage
    {
        public ItemDetailPage()
        {
            this.InitializeComponent();
        }

        /// <summary>
        /// Invoked when this page is about to be displayed in a Frame.
        /// </summary>
        /// <param name="e">Event data that describes how this page was reached.  The Parameter
        /// property provides the initial item to be displayed.</param>
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            var item = (SampleDataItem)e.Parameter;
            this.DefaultViewModel["Group"] = item.Group;
            this.DefaultViewModel["Items"] = item.Group.Items;
            this.flipView.SelectedItem = item;
        }

        private void albumListView_ItemClick_1(object sender, ItemClickEventArgs e)
        {
            if (App.MediaElement != null)
            {
                PivotItemViewModel pivm = (PivotItemViewModel)e.ClickedItem;
                var req = pivm.LoadItems();
                req.RunRequestCompleted += req_RunRequestCompleted;
                req.RunRequestAsync(pivm);
            }
        }

        void req_RunRequestCompleted(object sender, MichMan.Utilities.Requests.RunRequestCompletedEventArgs e)
        {
            GetMusicDirectoryRequest req = (GetMusicDirectoryRequest)sender;            
            DownloadFileRequest fileReq = new DownloadFileRequest(SubsonicRequestContext.StreamUrl(req.Response.Directory.Children[0].Id), req.Response.Directory.Children[0].Path);
            fileReq.RunRequestCompleted += fileReq_RunRequestCompleted;
            fileReq.RunRequestAsync();
        }

        async void fileReq_RunRequestCompleted(object sender, RunRequestCompletedEventArgs e)
        {
            DownloadFileRequest fileReq = (DownloadFileRequest)sender;

                    StorageFolder folder = await Package.Current.InstalledLocation.CreateFolderAsync("Music", CreationCollisionOption.OpenIfExists);
                    foreach (var f in System.IO.Path.GetDirectoryName(fileReq.Path).Split('\\'))
                    {
                        folder = await folder.CreateFolderAsync(f, CreationCollisionOption.OpenIfExists);
                    }
                    StorageFile file = await folder.CreateFileAsync(System.IO.Path.GetFileName(fileReq.Path));
                    var fileStream = await file.OpenAsync(FileAccessMode.ReadWrite);
                    Stream writeStream = fileStream.AsStreamForWrite();
                    fileReq.Response.CopyTo(writeStream);

                    writeStream.Flush();
                    await fileStream.FlushAsync();
                    writeStream.Dispose();
                    fileStream.Dispose();

            MediaElement snd = App.MediaElement;
            var stream = await file.OpenAsync(FileAccessMode.Read);
            snd.SetSource(stream, file.ContentType);
            snd.Play();
        }
    }

    class DownloadFileRequest : DataRequest<MemoryStream>
    {
        public string Path { get; set; }
        public DownloadFileRequest(string url, string path)
        {
            Uri = new Uri(url);
            Path = path;
        }

        protected override void ProcessResult(Stream stream)
        {
            MemoryStream memStream = new MemoryStream();
            stream.CopyTo(memStream);
            memStream.Seek(0, SeekOrigin.Begin);
            Response = memStream;
        }
    }
}
